<?php
/**
 * 解析控制器
 * @author sunhaoqiang(shqdev@163.com)
 * @time: 2019-11-29 11:45
*/
namespace script;

use script\DecoratorBase;
use script\Http;

class RouteAnalysis
{
    // 路由名称
    private $route_name;
    // 路由执行的类名
    private $route_cls;
    // 路由执行的类方法
    private $route_action;
    // 路由的来源
    private $route_from;
    // 路由的注册方式:配置文件注册，动态注册
    private $route_register_type;
    // 中间件
    public $middleware;
    
	public function __construct($route_name, $params, Array $from = [])
	{
		$this->init($route_name, $params, $from);
	}

    /**
     * 
     *
     * @param String $route_name    路由名称
     * @param String|Array $params  控制器、执行方法
     * @param Array $from   路由的注册来源
     * @return void
     * @author sunhaoqiang(shqdev@163.com)
     * @time 2019-12-27 17:02
     */
    private function init($route_name, $params, Array $from = [])
    {
        if (!empty($route_name)) {
            $this->route_name = $route_name;
        }
        
        if (is_string($params)) {
            [$this->route_cls, $this->route_action] = explode(':', $params);
        }

        if (is_array($params) && key_exists('controller', $params) && key_exists('action', $params)) {
            $this->route_cls = $params['controller'];
            $this->route_action = $params['action'];
        }

    }

    /**
     * 控制器执行方法
     *
     * @return void
     * @author sunhaoqiang(shqdev@163.com)
     * @time 2019-12-27 16:02
     */
    private function action()
    {
        if (empty($this->route_name)) {
            throw new \Exception("路由名称不能为空");
        }

        if (empty($this->route_cls) || empty($this->route_action)) {
            throw new \Exception("路由找不到");
        }

        $cls = new $this->route_cls;
        $action = $this->route_action;
        return $cls->$action();
    }

    public function add(DecoratorBase $middleware)
    {
        $this->middleware = $middleware;
        return $this;
    }

    /**
     * 解析路由并执行控制器
     *
     * @return void
     * @author sunhaoqiang(shqdev@163.com)
     * @time 2019-12-27 16:03
     */
    public function run()
    {
        if (!empty($this->middleware)) {
            $this->middleware->befer();
        }

        Http::set('result', $this->action());
        if (!empty($this->middleware)) {
            $this->middleware->after();
        }
        
    }
	
}
